import { ForwardRefRenderFunction, useEffect, memo, useImperativeHandle, forwardRef, useCallback, useMemo } from 'react'
import './style.less'
import { HsAdminForm, HsAdminInput } from '@hs-admin/base-components'
import { Button, Row, Col, Form, DatePicker, Space, message } from 'antd'
import { useImmer } from 'use-immer'
import dayjs from 'dayjs'
import { useTypeStore } from '@/store/useOperationDataItem'
import { HsAdminSelectDataItem } from '@/components/global'
import { reqDataItemInfo } from '@/api/assetMaintain/basic/item'

interface Props {
  dataItem: any
  back: () => void
  finish: (params: any) => void
}

const Step1: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const {
    dataItem: { id },
    back,
    finish
  } = props
  const setDataItemId = useTypeStore((state) => state.setDataItemId)
  const setDataItemInfor = useTypeStore((state) => state.setDataItemInfor)
  const setTabKey = useTypeStore((state) => state.setTabKey)
  const setSetp1Save = useTypeStore((state) => state.setSetp1Save)

  const [form] = Form.useForm()
  const [formValues, setformValues] = useImmer<any>({
    plans: [],
    helpers: []
  })

  const handleSelectTable = async (value: any) => {
    const params = {
      id: value
    }
    const data = await reqDataItemInfo(params)
    const model = {
      ...data,
      plans: [{ date: '', description: data.current_integrity }, ...data.plans]
    }
    setformValues(model)
    form.setFieldsValue(model)
    setDataItemId(model.id)
    setDataItemInfor(model)
  }

  const formItemOptions = useMemo(
    () => [
      {
        label: '数据项选择',
        name: 'select_table',
        slot: 'select_table',
        required: true,
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '数据项描述',
        name: 'description',
        component: 'TextArea',
        required: true,
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '',
        name: 'title',
        slot: 'title'
      },
      {
        label: '数据评分',
        name: 'score',
        component: 'InputNumber',
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '负责人',
        name: ['contacts', 'name'],
        component: 'Input',
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '更新周期',
        name: 'update_frequency',
        component: 'Input',
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '数据来源',
        name: 'source',
        component: 'Input',
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '区域范围',
        name: 'area_scope',
        component: 'Input',
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '数据时间范围',
        name: 'time_scope',
        component: 'Input',
        FormItemColProps: {
          span: 12
        },
        componentProps: {
          disabled: true
        }
      },
      {
        label: '完整度及计划',
        name: 'plans',
        slot: 'plans',
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        }
      },
      {
        label: '帮助及问题',
        name: 'helpers',
        slot: 'helpers',
        FormItemProps: {
          labelCol: { span: 3 },
          wrapperCol: { span: 21 }
        }
      }
    ],
    []
  )

  const goStep2 = async () => {
    if (!formValues.id) {
      message.warning('请选择数据项')
      return
    }
    setTabKey('2')
    setSetp1Save(true)
  }
  const cancel = useCallback(async () => {
    setformValues({})
    form.resetFields()
    setDataItemId(null)
  }, [form, setDataItemId, setformValues])
  const handleOk = () => {
    const select_table = form.getFieldValue('select_table')
    if (!select_table) {
      message.warning('请选择数据项')
      return
    }
    finish(formValues)
  }

  useEffect(() => {
    if (id) {
      const params = {
        id
      }
      reqDataItemInfo(params).then((res) => {
        const data = res
        const model = {
          ...data,
          plans: [{ date: '', description: data.current_integrity }, ...data.plans]
        }
        setformValues(model)
        form.setFieldsValue(model)
      })
    }
  }, [form, setformValues, id])

  useImperativeHandle(
    ref,
    () => {
      return {
        cancel
      }
    },
    [cancel]
  )

  return (
    <div className="operation-basic-data-item-setp1">
      <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} labelAlign="right">
        <div slot="select_table">
          <HsAdminSelectDataItem placeholder="请选择数据项" disabled={!!id} onChange={handleSelectTable} />
        </div>
        <div slot="title">
          <Row>
            <Col span={4}>
              <h3>数据项信息</h3>
            </Col>
          </Row>
        </div>
        <div slot="plans">
          <div>
            {formValues.plans?.map((item: any, index: number) => (
              <Row key={index} gutter={[12, 12]} className="plan-row">
                <Col span={8}>
                  {!index && <span>当前</span>}
                  {index > 0 && <DatePicker defaultValue={dayjs(item.date)} className="w-full" disabled></DatePicker>}
                </Col>
                <Col span={8}>
                  <HsAdminInput TextArea defaultValue={index ? item.description : formValues.current_integrity} disabled></HsAdminInput>
                </Col>
              </Row>
            ))}
          </div>
        </div>
        <div slot="helpers">
          <div>
            {formValues.helpers?.map((item: any, index: number) => (
              <Row key={index} gutter={[12, 12]} className="plan-row">
                <Col span={8}>
                  <div className="flex items-center">
                    <span className="flex-none">问题{index + 1}&nbsp;&nbsp;</span>
                    <HsAdminInput defaultValue={item.question} disabled></HsAdminInput>
                  </div>
                </Col>
                <Col span={8}>
                  <div className="flex items-center">
                    <span className="flex-none">回复&nbsp;&nbsp;</span>
                    <HsAdminInput TextArea defaultValue={item.answer} disabled></HsAdminInput>
                  </div>
                </Col>
              </Row>
            ))}
          </div>
        </div>
      </HsAdminForm>
      <Space className="flex justify-end">
        <Button onClick={back}>取消</Button>
        <Button type="primary" onClick={goStep2}>
          下一步
        </Button>
        <Button type="primary" onClick={() => handleOk()}>
          确定
        </Button>
      </Space>
    </div>
  )
}

export default memo(forwardRef(Step1))
